using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Context;
using Enums = PHSRAG.Security.Enumerations;
using Policy = PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.InsightWebControls
{
	/// <summary>
	/// Summary description for AdminSubNavigation.
	/// </summary>
	[ToolboxData("<{0}:AdminSubNavigation runat=server />")]
	[Designer(typeof(AdminSubNavigationDesigner), typeof(IDesigner))]
	public class AdminSubNavigation : SubNavigation
	{
		#region Constants
		private const string SelectedAdminSubNavigationLinkKey = "SelectedAdminubNavigationLink_4A91589B-9CAC-4dbd-9DA6-523D8E1D6A71";
		#endregion

		#region Instance Variables
		private Policy.ICachePolicy	cachePolicy;
		private LinkButton userManagementLinkButton;
		private LinkButton labManagementLinkButton;
		private LinkButton personnelManagementLinkButton;
		private LinkButton humansLinkButton;
		private LinkButton refCodeMgmtButton;
		private LinkButton sponsorAdditionLinkButton;
		private LinkButton animalsLinkButton;
		private LinkButton researchContactsManagementLinkButton;
		#endregion

		#region Properties
		/// <summary>
		/// Determines the selected tab
		/// </summary>
		public string SelectedTab
		{ 
			get {
				object o = Page.Session[SelectedAdminSubNavigationLinkKey];
				return (o != null)? (string)o : null;				
				}							
		}
		/// <summary>
		/// Return true if the control is in design mode.
		/// </summary>
		private static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}

		/// <summary>
		/// Determines if lab management tab should be made visible or not
		/// based on whether the logged in user is a keygiver or sys admin.
		/// </summary>
		private bool IsLabManagementVisible 
		{ 
			get 
			{
				UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
				return (userContext.ModuleRoleBitmask & (int)Enums.ModuleRoleBit.SystemAdministrator) != 0 ||
					userContext.IsKeyGiver;
			}
		}

		/// <summary>
		/// Determines if Humans management tab should be made visible or not
		/// based on whether the logged in user is a sys admin, a Forms Manager, a List Manager, or
		/// a Workflow Manager
		/// </summary>
		private bool IsHumansManagementVisible
		{ 
			get 
			{
				return ((((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask &
					((int)Enums.ModuleRoleBit.SystemAdministrator | 
					(int)Enums.ModuleRoleBit.FormsManager | (int)Enums.ModuleRoleBit.ListManager |
					(int)Enums.ModuleRoleBit.WorkflowManager)) != 0 );
			}
		}


		/// <summary>
		/// Determines if Refcode management tab should be made visible or not
		/// based on whether the logged in user is a sys admin, a Forms Manager, a List Manager, or
		/// a Workflow Manager
		/// </summary>
		private bool IsRefCodeManagementVisible
		{ 
			get 
			{
				return ((((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask &
					((int)Enums.ModuleRoleBit.RefcodeManager)) != 0 );
			}
		}

		///<summary>
		///Deteremines if the sponsor addition tab should  be made visible or not
		///System administrators or sponsor manager
		///</summary>
		private bool IsSponsorAdditionVisible
		{
			get
			{
				return ((((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask &
					((int)Enums.ModuleRoleBit.SystemAdministrator | (int)Enums.ModuleRoleBit.SponsorManager)) != 0); 
			}
		}

		/// <summary>
		/// Determines if Animals Management tab should be made visible or not 
		/// based on whether the logged in user has atleast ateast one of the following access rights:
		/// AnimalsManager,SysAdmin 
		/// </summary>
		private bool IsAnimalsManagementVisible 
		{ 
			get 
			{
				return ((((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask &
					((int)Enums.ModuleRoleBit.SystemAdministrator |	(int)Enums.ModuleRoleBit.AnimalsFormsManager |
                     (int)Enums.ModuleRoleBit.AnimalsWorkflowManager )) != 0 );
			}
		}

		/// <summary>
		/// Determines if Research Contacts Management tab should be made visible or not 
		/// based on whether the logged in user has atleast ateast one of the following access rights:
		/// ResearchContactsManager,SysAdmin 
		/// </summary>
		private bool IsResearchContactsManagementVisible 
		{ 
			get 
			{
				return ((((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask &
					((int)Enums.ModuleRoleBit.SystemAdministrator |	(int)Enums.ModuleRoleBit.ResearchContactsManager )) != 0 );
			}
		}
		
		#endregion

		#region Implementations for abstract properties and methods from Base Class SubNavigation

		/// <summary>
		/// Create all controls in the AdminSubNavigation.
		/// </summary>
		protected override void CreateControls()
		{
			Controls.Clear();

			userManagementLinkButton = new LinkButton();
			userManagementLinkButton.CommandName = userManagementLinkButton.Text = "User Management";
			userManagementLinkButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.UserManagementURL", "");
			userManagementLinkButton.CausesValidation = false;

			if (IsDesignMode || IsLabManagementVisible) 
			{
				labManagementLinkButton = new LinkButton();
				labManagementLinkButton.CommandName = labManagementLinkButton.Text = "Lab Management";
				labManagementLinkButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.LabManagementURL", "");
				labManagementLinkButton.CausesValidation = false;
			}

			personnelManagementLinkButton = new LinkButton();
			personnelManagementLinkButton.CommandName = personnelManagementLinkButton.Text = "Personnel Management";
			personnelManagementLinkButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.PersonnelManagementURL", "");
			personnelManagementLinkButton.CausesValidation = false;

           	if (IsDesignMode || IsSponsorAdditionVisible)
			{
				sponsorAdditionLinkButton = new LinkButton();
				sponsorAdditionLinkButton.CommandName = sponsorAdditionLinkButton.Text = "Sponsor Addition";
				sponsorAdditionLinkButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.SponsorAdditionURL", "");
				sponsorAdditionLinkButton.CausesValidation = false;
			}
			
			if (IsDesignMode || IsHumansManagementVisible)
			{
				humansLinkButton = new LinkButton();
				humansLinkButton.CommandName = humansLinkButton.Text = "Humans Management";
				humansLinkButton.CausesValidation = false;


				if (!IsDesignMode)
				{
					/* The landing page for the Humans Management subModule depends on which pages
					 * the current logged-in user has access to */
					int moduleRoleBitmask = 
						((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;

					if ((moduleRoleBitmask & 
						((int)Enums.ModuleRoleBit.FormsManager |(int)Enums.ModuleRoleBit.SystemAdministrator)) != 0)
						humansLinkButton.CommandArgument =
							Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.FormsManagementURL", "");
					else if ((moduleRoleBitmask & (int)Enums.ModuleRoleBit.ListManager) != 0)
						humansLinkButton.CommandArgument =
							Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.ListRequestURL", "");
					else 
						humansLinkButton.CommandArgument = 
							Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.WorkFlowManagerURL", "");
				}
			}

			if (IsDesignMode || IsRefCodeManagementVisible) 
			{
				refCodeMgmtButton = new LinkButton();
				refCodeMgmtButton.CommandName = refCodeMgmtButton.Text = "Refcode Management";
				refCodeMgmtButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.RefCodeManagementURL", "");
				refCodeMgmtButton.CausesValidation = false;
			}

			if (IsDesignMode || IsAnimalsManagementVisible)
			{
				animalsLinkButton = new LinkButton();
				animalsLinkButton.CommandName = animalsLinkButton.Text = "Animals Management";
				animalsLinkButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.Animals.FormsManagementURL", "");
				animalsLinkButton.CausesValidation = false;
			}

			if (IsDesignMode || IsResearchContactsManagementVisible)
			{
				researchContactsManagementLinkButton = new LinkButton();
				researchContactsManagementLinkButton.CommandName = researchContactsManagementLinkButton.Text = "Research Contacts Management";
				researchContactsManagementLinkButton.CommandArgument = Utility.Settings.GetKeyValue("SubNavigation.Admin.researchContactsManagementURL", "");
				researchContactsManagementLinkButton.CausesValidation = false;
			}
			
		}

		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the AdminSubNavigation.
		/// </summary>
		protected override void GenerateControlTree()
		{
			Table table = new Table();
			Controls.Add(table);
			table.CssClass = "SubModuleSummaryNavigation";

			TableRow row = new TableRow();
			table.Rows.Add(row);

			TableCell cell = new TableCell();
			row.Cells.Add(cell);
			cell.CssClass = "SubModuleSummaryNavigationFillerCell";
			cell.Controls.Add(new LiteralControl("&nbsp;"));

			cell = new TableCell();
			row.Cells.Add(cell);

			table = new Table();
			cell.Controls.Add(table);

			row = new TableRow();
			table.Rows.Add(row);

			cell = new TableCell();
			row.Cells.Add(cell);

			cell = new TableCell();
			row.Cells.Add(cell);
			cell.Controls.Add(userManagementLinkButton);

			if (IsDesignMode || IsLabManagementVisible) 
			{                			
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(labManagementLinkButton);
			}
			cell = new TableCell();
			row.Cells.Add(cell);
			cell.Controls.Add(personnelManagementLinkButton);

            if (IsDesignMode || IsHumansManagementVisible)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(humansLinkButton);
			}

			if (IsDesignMode || IsRefCodeManagementVisible) 
			{                			
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(refCodeMgmtButton);
			}
			if (IsDesignMode || IsSponsorAdditionVisible)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(sponsorAdditionLinkButton);
			}
			if (IsDesignMode || IsAnimalsManagementVisible)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(animalsLinkButton);
			}
			if (IsDesignMode || IsResearchContactsManagementVisible)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(researchContactsManagementLinkButton);
			}

			CreateSelectedLinkAdornments(row);
		}
		/// <summary>
		/// The selected link cell is given a prefix and suffix image as adornments. In addition the background of the
		/// cell is of a different style.
		/// </summary>
		private void CreateSelectedLinkAdornments(TableRow row)
		{
			LinkButton selectedLink = GetSelectedLink();
			foreach (TableCell cell in row.Cells)
			{
				if ((cell.Controls.Count == 1) && (cell.Controls[0] == selectedLink))
				{
					cell.CssClass = "SubModuleNavigationSelectedSummary";

					TableCell adornmentCell = new TableCell();
					adornmentCell.CssClass = "SubModuleNavigationSelectedSummaryAdornment";
					row.Cells.AddAt(row.Cells.GetCellIndex(cell), adornmentCell);

					const string prefixImage = "../Images/Row2_Left.gif";
					Image image = new Image();
					image.ImageUrl = prefixImage;
					if (!IsDesignMode)
						adornmentCell.Width = (new System.Drawing.Bitmap(Context.Server.MapPath(prefixImage))).Width;
					adornmentCell.Controls.Add(image);

					adornmentCell = new TableCell();
					adornmentCell.CssClass = "SubModuleNavigationSelectedSummaryAdornment";
					row.Cells.AddAt(row.Cells.GetCellIndex(cell) + 1, adornmentCell);

					const string suffixImage = "../Images/Row2_Right.gif";
					image = new System.Web.UI.WebControls.Image();
					image.ImageUrl = suffixImage;
					if (!IsDesignMode)
						adornmentCell.Width = (new System.Drawing.Bitmap(Context.Server.MapPath(suffixImage))).Width;
					adornmentCell.Controls.Add(image);

					break;
				}
			}
		}
		/// <summary>
		/// Retrieve the name of the link that was last clicked on.
		/// </summary>
		/// <returns>Reference to the link button corresponding to the clicked link</returns>
		protected override LinkButton GetSelectedLink()
		{
			// Anytime a link is clicked on, the OnBubbleEvent handler stores the name of the link in the session. Retrieve
			// that name and return the corresponding link button reference.

			if (!IsDesignMode)
			{
				string commandName = SelectedTab;
				if (commandName != null)
				{
					if (commandName == userManagementLinkButton.CommandName)
						return userManagementLinkButton;				
					if (commandName == personnelManagementLinkButton.CommandName)
						return personnelManagementLinkButton;
                   	if ((labManagementLinkButton != null) && (commandName == labManagementLinkButton.CommandName))
						return labManagementLinkButton;
					if ((humansLinkButton != null) && (commandName == humansLinkButton.CommandName))
						return humansLinkButton;
					if ((refCodeMgmtButton != null) && (commandName == refCodeMgmtButton.CommandName))
						return refCodeMgmtButton;
					if ((sponsorAdditionLinkButton != null) && (commandName == sponsorAdditionLinkButton.CommandName))
						return sponsorAdditionLinkButton;
					if ((animalsLinkButton != null) && (commandName == animalsLinkButton.CommandName))
						return animalsLinkButton;
					if ((researchContactsManagementLinkButton != null) && (commandName == researchContactsManagementLinkButton.CommandName))
						return researchContactsManagementLinkButton;
				}
			}
			return userManagementLinkButton;
		}
		
		
		/// <summary>
		/// 
		/// </summary>
		protected override string SelectedSubNavigationLinkKey
		{
			get 
			{
				return SelectedAdminSubNavigationLinkKey;
			}
		}
				
		#region Event Handlers
		/// <summary>
		/// Disable view state.
		/// </summary>
		/// <param name="e">Argument associated with the load event.</param>
		protected override void OnLoad(EventArgs e)
		{
			EnableViewState = false;
			base.OnLoad (e);	
		}
		#endregion
		
		/// <summary>
		/// Initialize the Cache Policy since OnLoad doesn't get called.
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnInit(EventArgs e)
		{
			base.OnInit (e);
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
		}
		#endregion
		
	}
	
	#region Class AdminSubNavigationDesigner
	/// <summary>
	/// Designer associated with the control.
	/// </summary>
	public class AdminSubNavigationDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the control</returns>
		public override string GetDesignTimeHtml()
		{
			((AdminSubNavigation)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}
